import type {
  ChatHistoryWin,
  ChatHistoryList,
  CategorizedChats,
} from "@/types";
import { useGeneralDataStore } from "@/store";
import {
  saveSession,
  getSession,
  deleteSession,
  getAllSessions,
  chatCache,
} from "@/utils";

export const useChatDataStore = defineStore(
  "ChatData",
  () => {
    const generalDataStore = useGeneralDataStore();
    // 聊天记录窗口
    const chatHistoryWin = ref<ChatHistoryWin[]>([]);
    // 重新生成的聊天记录
    const regenerateHistoryChat = ref<Map<number, ChatHistoryWin[]>>();
    // 当前聊天ID
    const currentChatId = ref<string | null>(null);
    // 当前会话
    const currentSession = ref<ChatHistoryList>();
    // 分类后的聊天记录
    const categorizedChats = ref<CategorizedChats[]>([]);
    // 生成的消息 ID
    const generatingMessageId = ref<string | null>(null);
    // 添加新聊天记录到列表
    const addNewChatHistory = async (name: string) => {
      const id = crypto.randomUUID();
      const newChat = {
        name,
        id: id,
        createdAt: new Date(),
        chatHistory: [...chatHistoryWin.value],
      };
      categorizedChats.value.unshift({
        timeName: "",
        thisChats: [newChat],
      });
      // 设置当前聊天ID
      currentChatId.value = id;
      // 设置当前会话
      currentSession.value = newChat;
      chatCache.set(id, newChat);
      await saveSession(newChat);
      return id;
    };

    // 加载指定聊天记录到当前窗口
    const loadChatHistory = async (id: string) => {
      let chat = chatCache.get(id);
      if (!chat) {
        chat = await getSession(id);
        if (chat) {
          chatCache.set(id, chat);
        }
      }
      if (chat) {
        currentChatId.value = id;
        currentSession.value = chat;
        chatHistoryWin.value = [...chat.chatHistory];
      }
    };

    // 更新当前聊天名称
    const updateCurrentChatName = async (id: string, newName: string) => {
      let chat = chatCache.get(id);
      if (!chat) {
        chat = await getSession(id);
      }
      if (chat) {
        chat.name = newName;
        chat.createdAt = new Date();
        chatCache.set(id, chat);
        await saveSession(chat);
        if (currentSession.value?.id === id) {
          currentSession.value.name = newName;
        }
      }
    };

    // 删除指定聊天记录
    const deleteChatHistory = async (id: string) => {
      const index = categorizedChats.value.findIndex((item) =>
        item.thisChats.some((i) => i.id === id)
      );
      if (index !== -1) categorizedChats.value.splice(index, 1);

      if (currentChatId.value === id) {
        generalDataStore.chatInput = "";
        chatHistoryWin.value = [];
        currentChatId.value = null;
        currentSession.value = undefined;
        generatingMessageId.value = null;
      }
      chatCache.delete(id);
      await deleteSession(id);
    };

    // 加载全部会话
    const loadAllSessions = async () => {
      const sessions = await getAllSessions();
      console.log("sessions", sessions);
      categorizedChats.value = sessions.map((session) => ({
        timeName: "",
        thisChats: [session],
      }));
      sessions.forEach((session) => {
        chatCache.set(session.id, session);
      });
    };

    return {
      chatHistoryWin,
      regenerateHistoryChat,
      currentChatId,
      currentSession,
      categorizedChats,
      generatingMessageId,
      addNewChatHistory,
      loadChatHistory,
      updateCurrentChatName,
      deleteChatHistory,
      loadAllSessions,
    };
  },
  { persist: true }
);
